package com.zy.mydemo.common.utils;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.util.StringUtils;

import java.util.Random;

/**
 * @Author:zhongyong
 * @Description：
 * @Date：Create in 2020/05/03
 */
public class PasswordUtils {
    /**
     * 加密算法
     */
    public final static String HASH_ALGORITHM_NAME = "SHA-256";
    /**
     * 加密次数
     */
    public final static int HASH_ITERATIONS = 5;

    /**
     * 对密码进行加密
     *
     * @param password
     * @param salt
     * @return
     */
    public final static String encrypt(String password, String salt) {
        SimpleHash simpleHash = new SimpleHash(PasswordUtils.HASH_ALGORITHM_NAME, password, salt, PasswordUtils.HASH_ITERATIONS);
        return simpleHash.toHex();
    }

    /**
     * 生成密码salt
     * @param length
     * @return
     */
    public final static String getSalt(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

}
